package dao

import (
	"douyin/log"
	"douyin/model"
	"douyin/utils/cache"
	"douyin/utils/cache/lru"
	"fmt"
	"strconv"
	"time"
)

func init() {
	// 创建缓存实例
	cacheGroup = make(map[string]*cache.Group)
	favoriteCache := cache.NewGroup("favorite", 100, favoriteCountLoad, favoriteCountPersist)
	followCountCache := cache.NewGroup("follow", 100, followCountLoad, followCountPersist)
	commentCountCache := cache.NewGroup("comment", 100, commentCountLoad, commentCountPersist)

	// 添加缓存到 cacheGroup 中 方便 dao 层其他操作访问
	cacheGroup["favorite"] = favoriteCache
	cacheGroup["follow"] = followCountCache
	cacheGroup["comment"] = commentCountCache
}

// 从缓存里面加载视频的点赞数量
func favoriteCountLoad(key string) ([]byte, error) {
	var v model.Video
	err := db.Model(&model.Video{}).Select("favorite_count").Where("video_id=?", key).First(&v).Error
	if err != nil {
		return nil, err
	}
	return cache.Int64ToBytes(int64(v.FavoriteCount)), nil
}

// 点赞数量持久化
func favoriteCountPersist(key string, value lru.Value) {
	id, _ := strconv.ParseInt(key, 10, 64)
	v := cache.BytesToInt64(value.(cache.ByteView).ByteSlice())
	err := NewVideo().UpdateVideoInfo(model.Video{VideoID: id, FavoriteCount: int32(v)})
	if err != nil {
		fmt.Println(err)
	}
}

// 关注数量-加载缓存方法
func followCountLoad(key string) ([]byte, error) {
	var u model.User
	err := db.Model(&model.User{}).Select("follow_count").Where("user_id = ?", key).First(&u).Error
	if err != nil {
		return nil, err
	}
	return cache.Int64ToBytes(u.FollowCount), nil
}

// 用户关注数量持久化，将缓存内容刷新到数据库
func followCountPersist(key string, value lru.Value) {
	id, _ := strconv.ParseInt(key, 10, 64)
	v := cache.BytesToInt64(value.(cache.ByteView).ByteSlice())
	err := NewUser().IncreaseFollowCount(id, v)
	if err != nil {
		// 日志模块
	}
}

// 加载评论数量
func commentCountLoad(key string) ([]byte, error) {
	var v model.Video
	err := db.Model(model.Video{}).Select("comment_count").Where("video_id=?", key).First(&v).Error

	return cache.Int64ToBytes(int64(v.CommentCount)), err
}

// 评论数量持久化
func commentCountPersist(key string, value lru.Value) {
	id, _ := strconv.ParseInt(key, 10, 64)
	v := cache.BytesToInt64(value.(cache.ByteView).ByteSlice())
	err := NewVideo().AddComment(id, int(v))

	if err != nil {
		// 日志模块
	}
}

// 定时刷新数据到mysql 进行数据的持久化
func persistData() {
	log.SugarLogger.Info("data persist start")
	time.AfterFunc(20*time.Second, func() {
		// TODO
	})
}
